package com.maserb.monitor.thymeleaf.dialect;

import com.maserb.monitor.entity.DeviceCategoryItemEntity;
import com.maserb.monitor.model.CustomItemModel;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;
import org.unbescape.html.HtmlEscape;

public class DeviceCategoryAttributeTagProcessor extends AbstractAttributeTagProcessor {
    private static final String ATTR_NAME = "device_category";
    private static final int PRECEDENCE = 10000;

    public DeviceCategoryAttributeTagProcessor(final String dialectPrefix) {
        super(
                TemplateMode.HTML,
                dialectPrefix,
                null,
                false,
                ATTR_NAME,
                true,
                PRECEDENCE,
                true);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag iProcessableElementTag, AttributeName attributeName,
                             String attributeValue, IElementTagStructureHandler structureHandler) {

        final IEngineConfiguration configuration = context.getConfiguration();

        final IStandardExpressionParser parser =
                StandardExpressions.getExpressionParser(configuration);

        final IStandardExpression expression = parser.parseExpression(context, attributeValue);

        final CustomItemModel entity = (CustomItemModel) expression.execute(context);
        String html = "";
        if (entity != null) {
            if (entity.getMode() == 1) {
                html += "<input type='text' name='" + entity.getName() + "' value='" + entity.getValue() + "' />";
            }
        }
        structureHandler.setBody(html, false);
    }
}
